package com.yzs.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sun.org.apache.xpath.internal.operations.Or;
import com.yzs.common.bean.R;
import com.yzs.entity.*;
import com.yzs.mapper.AdminMapper;
import com.yzs.mapper.HouseMapper;
import com.yzs.mapper.OrderMapper;
import com.yzs.mapper.UserMapper;
import com.yzs.service.IOrderService;
import com.yzs.utils.JwtUtil;
import com.yzs.utils.TimeUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Objects;


@Service
public class OrderServiceImpl implements IOrderService {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    HouseMapper houseMapper;
    @Autowired
    AdminMapper adminMapper;
    @Autowired
    JwtUtil JwtUtil;

    @Override
    public R createOrder(String hId, Integer sId, Integer bId, Integer aId) {
        // 判断是否存在订单
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("h_id", hId).eq("b_id", bId);
        Order o = orderMapper.selectOne(orderQueryWrapper);
        if (o != null) {
            return R.error("订单已存在，请联系卖家或经理！");
        }
        Order order = new Order();
        if (sId == -1 && aId == -1) {
            return R.error("卖家或经理信息错误，请联系卖家或经理！");
        }
        if (sId != -1) {
            order.setSId(sId);
        }
        if (aId != -1) {
            order.setAId(aId);
        }
        // 生成订单号
        long v = (long) (Math.random() * (99999 - 10000) + 10000);
        long l = System.currentTimeMillis();
        String oId = String.valueOf(l) + String.valueOf(v);
        order.setOId(oId);
        order.setBId(bId);
        order.setHId(hId);
        order.setCreateTime(TimeUtil.getNowTime());
        order.setStep(1);
        int i = orderMapper.insert(order);
        if (i == 1) {
            return R.ok("已生成订单，请联系卖家或者经理进一步沟通！");
        }
        return R.error("订单生成失败，请重试！");
    }

    @Override
    public R getMyOrder(Integer id) {
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("b_id", id);
        List<Order> orders = orderMapper.selectList(orderQueryWrapper);
        for (Order order : orders) {
            HashMap<String, Object> map = new HashMap<>();
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            QueryWrapper<Admin> adminQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.select("name", "phone").eq("id", order.getSId());
            adminQueryWrapper.select("name", "phone").eq("id", order.getAId());
            House house = houseMapper.selectById(order.getHId());
            User user = userMapper.selectOne(userQueryWrapper);
            Admin admin = adminMapper.selectOne(adminQueryWrapper);
            map.put("house", house);
            map.put("saler", user);
            map.put("admin", admin);
            order.setInformation(map);
        }
        return R.ok(orders);
    }

    @Override
    public R getMySaleOrder(Integer id) {
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("s_id", id);
        List<Order> orders = orderMapper.selectList(orderQueryWrapper);
        for (Order order : orders) {
            HashMap<String, Object> map = new HashMap<>();
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            QueryWrapper<Admin> adminQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.select("name", "phone").eq("id", order.getBId());
            adminQueryWrapper.select("name", "phone").eq("id", order.getAId());
            House house = houseMapper.selectById(order.getHId());
            User user = userMapper.selectOne(userQueryWrapper);
            Admin admin = adminMapper.selectOne(adminQueryWrapper);
            map.put("house", house);
            map.put("buyer", user);
            map.put("admin", admin);
            order.setInformation(map);
        }
        return R.ok(orders);
    }

    @Override
    public R nextStep(String oId, Integer step) {
        Order order = orderMapper.selectById(oId);
        order.setStep(step + 1);
        int i = 0;
        if(order.getStep() == 6){
            UpdateWrapper<House> houseUpdateWrapper = new UpdateWrapper<>();
            houseUpdateWrapper.eq("id",order.getHId()).set("house_status",2);
            int update = houseMapper.update(null, houseUpdateWrapper);
            if (update == 1){
                i = orderMapper.updateById(order);
            }else{
                return R.error();
            }
        }else {
            i = orderMapper.updateById(order);
            if (i == 1) {
                return R.ok();
            }else {
                return R.error();
            }
        }
        return R.error();
    }

    @Override
    public R getOrderByRolePage(String token, Integer currentPage, Integer pageSize) {
        Claims body = JwtUtil.getTokenAdminInfo(token).getBody();
        String role = String.valueOf(body.get("role"));
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        if (role.isEmpty()) {
            return R.error();
        } else if ("Manager".equals(role)) {
            Integer id = (Integer) body.get("id");
            wrapper.eq("a_id", id);
        } else {
            wrapper.isNotNull("o_id");
        }
        Page<Order> page = new Page<>(currentPage, pageSize);
        page = orderMapper.selectPage(page, wrapper);
        if (page.getRecords().isEmpty()) {
            return R.error("no data！");
        } else {
            for (Order o : page.getRecords()) {
                QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
                userQueryWrapper.select("id", "name", "phone").eq("id", o.getBId());
                if (Objects.nonNull(o.getSId())) {
                    userQueryWrapper.or().eq("id", o.getSId());
                }
                for (User user : userMapper.selectList(userQueryWrapper)) {
                    if (user.getId().equals(o.getBId())) {
                        o.getInformation().put("buyer", user);
                    } else {
                        o.getInformation().put("saler", user);
                    }
                }
                House house = houseMapper.selectById(o.getHId());
                o.getInformation().put("house", house);
                if (Objects.nonNull(o.getAId())) {
                    Admin admin = adminMapper.selectById(o.getAId());
                    o.getInformation().put("admin", admin);
                }
            }

        }
        PageResult<Order> data = new PageResult<>(page.getTotal(), page.getRecords());
        return R.ok(data);
    }

    @Override
    public R deleteOrder(String id) {
        int i = orderMapper.deleteById(id);
        if (i == 1) {
            // 删除成功
            return R.ok("删除成功！");
        } else {
            return R.error("删除失败！");
        }
    }

    @Override
    public R editOrderStep(String oid, Integer step) {
        UpdateWrapper<Order> orderUpdateWrapper = new UpdateWrapper<>();
        orderUpdateWrapper.set("step", step).eq("o_id", oid);
        int i = orderMapper.update(null, orderUpdateWrapper);
        if (i == 1) {
            Order order = orderMapper.selectById(oid);
            if (step == 6){
                UpdateWrapper<House> houseUpdateWrapper = new UpdateWrapper<>();
                houseUpdateWrapper.set("house_status", 2).eq("id", order.getHId());
                int update = houseMapper.update(null, houseUpdateWrapper);
                if (update == 1) {
                    return R.ok("订单当前状态修改成功！");
                }else {
                    return R.error("当前房屋信息有问题，请联系卖家或管理员！");
                }
            }else {
                UpdateWrapper<House> houseUpdateWrapper = new UpdateWrapper<>();
                houseUpdateWrapper.set("house_status", 1).eq("id", order.getHId());
                int update = houseMapper.update(null, houseUpdateWrapper);
                if (update == 1) {
                    return R.ok("订单当前状态修改成功！");
                }else {
                    return R.error("当前房屋信息有问题，请联系卖家或管理员！");
                }
            }
        } else {
            return R.error("订单当前状态修改删除失败！");
        }
    }
}
